package com.ctgu.redislock02.rabbitmq;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ctgu.redislock02.entity.ProductsEntity;
import com.ctgu.redislock02.mapper.ProductsMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @ ClassName ProductOrderConsumer
 * @ Author Alex2
 * @ Date 2025/9/10 17:00
 **/
@Component
@Log4j2
public class ProductOrderConsumer {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private ProductsMapper productsMapper;

    private static final String TAG = "ALEX";
    private static final String REDIS_KEY_STOCK_PRODUCTS = "stock:product:";

    // 削峰 + 异步 + 保证消息可靠性
    @RabbitListener(queues = RabbitMQConfig.QUEUE_PRODUCT_ORDER)
    public void handle(Integer id) {

        String stockStr = redisTemplate.opsForValue().get(REDIS_KEY_STOCK_PRODUCTS + id);
        if (stockStr == null || Integer.parseInt(stockStr) <= 0) {
            log.warn("{} : {}", TAG, "库存不足，productId");
            return;
        }

        // 扣减库存，保证事务回滚
        try {
            transactionTemplate.execute(status -> {
                int updated = productsMapper.update(null,
                        new LambdaUpdateWrapper<ProductsEntity>()
                                .setSql("stock = stock - 1")
                                .eq(ProductsEntity::getId, id)
                                .gt(ProductsEntity::getStock, 0)
                );
                if (updated == 0) {
                    log.error("{} : {}", TAG, "数据库库存扣减失败");
                    throw new RuntimeException("数据库库存扣减失败"); // 事务会回滚
                }
                return null;
            });
        } catch (RuntimeException e) {
            log.error("扣减库存失败，productId={}, error={}", id, e.getMessage());
        }
    }
}